using Autofac;
using Microsoft.Extensions.FileProviders;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Datav.Design.CmdExecutor;
using Datav.Design.Core.Extensions;

//using IP2Region.Net.Abstractions;
//using IP2Region.Net.XDB;
using Zdap.Common;
using Zdap.Common.API.Extensions;

//namespace Datav.Design.web.api
//{
//    public class Program
//    {
//        public static void Main(string[] args)
//        {
#if DEBUG
Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", Environments.Development);//设置环境变量为Development //builder.Host.UseEnvironment(Environments.Development);
#endif

var builder = WebApplication.CreateBuilder(args);

//禁用模型过滤，如：string 为空必传 禁用
builder.Services.Configure<Microsoft.AspNetCore.Mvc.ApiBehaviorOptions>(options => options.SuppressModelStateInvalidFilter = true);

// 添加 Http API 接口调用客户端
//builder.Services.AddHttpClients(builder.Configuration);

// Add services to the container.
builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();

//加载Ip 定位
//builder.Services.AddSingleton<ISearcher>(new Searcher(new CachePolicy(), Environment.CurrentDirectory + @"/IpData/ip2region.xdb"));
// 注册 CommandExecutorService 服务
builder.Services.AddSingleton<CommandExecutorService>();

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen();

builder.Services.AddCommonServices(builder, "API");

///
builder.Services.AddSingleton(new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(CommonConstants.IdentServerSecret)), SecurityAlgorithms.HmacSha256));

builder.Host.UseServiceProviderFactory(new Autofac.Extensions.DependencyInjection.AutofacServiceProviderFactory())//使用Autofac DI注入
   .UseSerilog()//Serilog记录日志
   .ConfigureContainer<ContainerBuilder>(builder =>
   {
       var assemblies = new System.Reflection.Assembly[] {
                         System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyName(new System.Reflection.AssemblyName("Datav.Design"))
       };

       builder.RegisterBusinessService(assemblies);//业务服务DL注入
       builder.RegisterType<SerilogLogger>().As<Zdap.Common.ILogger>().SingleInstance();//日志类注入
   });

//#if DEBUG
//#endif

NewLife.Log.XTrace.UseConsole();

var app = builder.Build();

app.UseRedis(app.Configuration["RedisConnection"]);

//app.UseFreeSqlRepository(app.Configuration.GetSection("ConnectionStrings:Datav.DesignLog:connectionString").Value, app.Configuration.GetSection("ConnectionStrings:Datav.DesignLog:connectionString").Value);

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

//app.UseCors("*"); // 应用CORS策略

app.UseCommonMiddleware(app.Environment, app.Configuration);//加载通用中间件

app.UseStaticFiles().UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true });

app.UseDefaultFiles();

//2021.06.27增加创建默认upload文件夹
string _uploadPath = (app.Environment.ContentRootPath + "/Uploads").ReplacePath();

if (!Directory.Exists(_uploadPath))
{
    Directory.CreateDirectory(_uploadPath);
}
//app.UseCors("AllowSpecificOrigin"); // 应用CORS策略

app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(
    Path.Combine(Directory.GetCurrentDirectory(), @"Uploads")),
    //配置访问虚拟目录时文件夹别名
    RequestPath = "/Upload",
    OnPrepareResponse = (Microsoft.AspNetCore.StaticFiles.StaticFileResponseContext staticFile) =>
    {
        //可以在此处读取请求的信息进行权限认证
        //  staticFile.File
        //  staticFile.Context.Response.StatusCode;
    }
});

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();